package com.zy;

import dev.langchain4j.community.model.dashscope.QwenEmbeddingModel;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.model.output.Response;

import java.util.List;

/**
 * @program: AI_langchain4j
 * @description: RAG示例1
 * @author: zy
 * @create: 2025-07-05 16:02
 */
public class RAG_App1 {
    public static void main( String[] args )
    {
        //1。文本向量化
        QwenEmbeddingModel qwenEmbeddingModel = QwenEmbeddingModel.builder()
                .apiKey(System.getenv("ALI_AI_KEY"))
                .build();
        //文本向量化
        Response<Embedding> embed=qwenEmbeddingModel.embed("这是一只漂亮的小狗");
        System.out.println(embed.content().toString());   //向量值
        System.out.println(   embed.content().vector().length );  //向量长度 维度

//        //1. 相似度比较
        Embedding emb1 = qwenEmbeddingModel.embed("这是一只小狗").content();
        Embedding emb2 = qwenEmbeddingModel.embed("那是一条狗").content();
        Embedding emb3 = qwenEmbeddingModel.embed("今天天气真好").content();
//
        double sim = cosineSimilarity( emb3.vectorAsList(), embed.content().vectorAsList());
        System.out.println("相似度：" + sim);   // 0.8976776706934477     0.7915839531806371   0.5304280499606998
//
//        sim = cosineSimilarity( emb1.vectorAsList(), emb3.vectorAsList());
//        System.out.println("相似度：" + sim);

    }

    public static double cosineSimilarity(List<Float> a, List<Float> b) {
        if (a.size() != b.size()) {
            throw new IllegalArgumentException("向量维度不一致");
        }

        double dotProduct = 0.0;
        double normA = 0.0;
        double normB = 0.0;

        for (int i = 0; i < a.size(); i++) {
            double x = a.get(i);
            double y = b.get(i);
            dotProduct += x * y;
            normA += x * x;
            normB += y * y;
        }

        if (normA == 0.0 || normB == 0.0) return 0.0;

        return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
    }
}
